package leecode

func nextGreaterElements(nums []int) []int {
	stack := make([]int, 0) //栈内存放数组元素的下标
	result := make([]int, len(nums)*2)
	for i := range result {
		result[i] = -1
	}
	size := len(nums)
	for i := 0; i < size; i++ {
		nums = append(nums, nums[i])
	}
	stack = append(stack, 0)
	for i := 1; i < len(nums); i++ {
		//栈顶元素的下标
		topIndex := stack[len(stack)-1]
		if nums[i] > nums[topIndex] {
			for len(stack) != 0 && nums[i] > nums[topIndex] {
				result[topIndex] = nums[i]
				//栈顶元素弹出栈
				stack = stack[:len(stack)-1]
				if len(stack) != 0 {
					topIndex = stack[len(stack)-1]
				}
			}
			stack = append(stack, i)
		} else {
			stack = append(stack, i)
		}
	}
	return result[:size]
}
